package com.example.forum.service.imp;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.mapper.MessageMapper;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.service.IMessageService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Reader;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MessageService implements IMessageService {
    @Autowired
    private UserServiceImp userServiceImp;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public void create(Message message) {
        //校验参数
        if(message == null
                || message.getPostUserId() == null
                || message.getReceiveUserId() == null
                || !StringUtils.hasLength(message.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //校验接收者是否存在
        User recevieUser = userServiceImp.selectById(message.getReceiveUserId());
        if(recevieUser == null || recevieUser.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }


        //设置默认值
        message.setState((byte)0);
        message.setDeleteState((byte)0);
        //设置更新时间
        message.setUpdateTime(new Date());
        message.setCreateTime(new Date());

        //判断是否插入成功
        int row = messageMapper.insertSelective(message);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        if (receiveUserId == null || receiveUserId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 直接调用DAO
        Integer count = messageMapper.selectUnreadCount(receiveUserId);
        // 正常的查询是不可能出现null，如果为null则抛出异常
        if (count == null) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        // 返回结果
        return count;
    }

    @Override
    public List<Message> selectByReceiveId(Long receiveUserId) {
        if (receiveUserId == null || receiveUserId <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 调用DAO
        List<Message> messages = messageMapper.selectByReceiveId(receiveUserId);
        // 返回结果
        return messages;
    }

    @Override
    public void updateStateById(Long id, Byte state) {
        //进行参数的校验
        if(id == null || id <= 0 || state < 0 || state > 2){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Message updateMessage = new Message();

        updateMessage.setId(id);
        updateMessage.setState(state);
        Date date = new Date();
        updateMessage.setUpdateTime(date);

        //调用dao
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Message selectById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }

    @Override
    public void reply(Long repliedId, Message message) {
        if (repliedId == null || repliedId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验repliedId对应的站内信状态
        Message existsMessage = messageMapper.selectByPrimaryKey(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        updateStateById(repliedId,(byte) 2);

        create(message);

    }


}
